﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using Technullogy.Web.UI.Weather.TechnullogyWeather;
using Technullogy.Web.UI.TwcWeather;
using System.Web.UI;

namespace Technullogy.Web.UI.Weather
{
    internal static class WeatherManager
    {
        internal static XmlDocument LoadTwcIntoXmlDoc(Uri twcUri, bool enableCaching, string locationId, Units displayUnits)
        {
            // Load up the weather!
            XmlDocument xmlDoc = new XmlDocument();

            String CACHE_FORMAT = "TechnullogyCache:{0}-{1}";
            // Load xmlDoc from Weather.com feed
            if ((HttpContext.Current == null))
                xmlDoc.Load(twcUri.ToString());
            else if (enableCaching)
            {
                if ((HttpContext.Current.Cache[String.Format(CACHE_FORMAT, locationId, displayUnits)] == null))
                {
                    xmlDoc.Load(twcUri.ToString());
                    HttpContext.Current.Cache.Insert(String.Format(CACHE_FORMAT, locationId, displayUnits), xmlDoc, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
                }
                else
                    xmlDoc = (XmlDocument)HttpContext.Current.Cache[String.Format(CACHE_FORMAT, locationId, displayUnits)];
            }
            else
                xmlDoc.Load(twcUri.ToString());

            return xmlDoc;
        }

        internal static XmlDocument LoadTwcSearchIntoXmlDoc(Uri twcSearchUri, bool enableCaching, String query)
        {
            // Load up the weather!
            XmlDocument xmlDoc = new XmlDocument();

            String CACHE_FORMAT = "TechnullogyQueryCache:{0}";

            // Load xmlDoc from Weather.com feed
            if ((HttpContext.Current == null))
                xmlDoc.Load(twcSearchUri.ToString());
            else if (enableCaching)
            {
                if ((HttpContext.Current.Cache[String.Format(CACHE_FORMAT, query)] == null))
                {
                    xmlDoc.Load(twcSearchUri.ToString());
                    HttpContext.Current.Cache.Insert(String.Format(CACHE_FORMAT, query), xmlDoc, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
                }
                else
                    xmlDoc = (XmlDocument)HttpContext.Current.Cache[String.Format(CACHE_FORMAT, query)];
            }
            else
                xmlDoc.Load(twcSearchUri.ToString());

            return xmlDoc;
        }

    }
}
